package com.ezcloud.server;

import com.ezcloud.engine.rpc.RpcProtocol;
import com.ezcloud.engine.rpc.serialize.kryo.KryoSerializationImpl;
import com.ezcloud.engine.rpc.server.RpcHandlerImpl;
import com.ezcloud.engine.rpc.server.RpcProtocolImpl;
import com.ezcloud.engine.rpc.server.RpcProtocolProcessorImpl;
import com.ezcloud.engine.rpc.server.RpcServerHandler;
import com.ezcloud.engine.server.NettyServer;
import com.ezcloud.engine.server.NettyServerOptions;
import com.ezcloud.server.simple.HelloExtImpl;
import com.ezcloud.server.simple.HelloImpl;
import com.ezcloud.simple.Hello;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

/**
 * @author : zuodp
 * @version : 1.10
 */
@SpringBootApplication
public class ServerBootstrap implements CommandLineRunner {

    public ServerBootstrap() {
    }

    @Override
    public void run(String... args) throws Exception {
        NettyServer nettyServer = new NettyServer(new NettyServerOptions());
        nettyServer.serve(9000, this::serverHandler);
        nettyServer.waitForClose();
    }

    protected RpcServerHandler serverHandler() {
        RpcHandlerImpl rpcHandler = new RpcHandlerImpl();
        rpcHandler.addExport("/v1", Hello.class, new HelloImpl());
        rpcHandler.addExport("/v2", Hello.class, new HelloExtImpl());

        RpcProtocol normalRpcCodeProtocol = new RpcProtocolImpl(KryoSerializationImpl::new);

        RpcProtocolProcessorImpl protocolProcessor = new RpcProtocolProcessorImpl();
        protocolProcessor.addRpcProtocol(normalRpcCodeProtocol);
        protocolProcessor.setRpcHandler(rpcHandler);
        return new RpcServerHandler(protocolProcessor);
    }

    public static void main(String[] args) throws InterruptedException {
        new SpringApplicationBuilder(ServerBootstrap.class).run(args);
    }
}
